<template>
  <div class="register-container">
    <div class="left-section">
      <div class="content">
        <h1>秒杀商城</h1>
        <p>注册即享优惠，开启您的购物之旅</p>
      </div>
    </div>
    <div class="right-section">
      <div class="register-form">
        <h2>账号注册</h2>
        <form @submit.prevent="handleRegister">
          <div class="form-group">
            <input 
              type="text" 
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              :class="{ 'error': phoneError }"
            >
            <span class="error-message" v-if="phoneError">{{ phoneError }}</span>
          </div>
          <div class="form-group verify-code">
            <input 
              type="text" 
              v-model="registerForm.code"
              placeholder="请输入验证码"
              :class="{ 'error': codeError }"
            >
            <button 
              type="button" 
              class="code-btn" 
              :disabled="isCountingDown"
              @click="sendCode"
            >
              {{ countDownText }}
            </button>
            <span class="error-message" v-if="codeError">{{ codeError }}</span>
          </div>
          <div class="form-group">
            <input 
              type="password" 
              v-model="registerForm.password"
              placeholder="请设置密码"
              :class="{ 'error': passwordError }"
            >
            <span class="error-message" v-if="passwordError">{{ passwordError }}</span>
          </div>
          <div class="form-group">
            <input 
              type="password" 
              v-model="registerForm.confirmPassword"
              placeholder="请确认密码"
              :class="{ 'error': confirmPasswordError }"
            >
            <span class="error-message" v-if="confirmPasswordError">{{ confirmPasswordError }}</span>
          </div>
          <div class="agreement-group">
            <label>
              <input 
                type="checkbox" 
                v-model="registerForm.agreement"
              >
              我已阅读并同意
              <a href="javascript:;" @click="showAgreement">《用户协议》</a>
              和
              <a href="javascript:;" @click="showPrivacy">《隐私政策》</a>
            </label>
            <span class="error-message" v-if="agreementError">{{ agreementError }}</span>
          </div>
          <button type="submit" class="register-btn" :disabled="loading">
            <span v-if="loading" class="loading-spinner"></span>
            注册
          </button>
          <div class="login-link">
            已有账号？<router-link to="/login">立即登录</router-link>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const registerFormRef = ref(null)

// 注册表单数据
const registerForm = ref({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 验证码倒计时
const countdown = ref(0)
const isCountingDown = computed(() => countdown.value > 0)
const countDownText = computed(() => 
  isCountingDown.value ? `${countdown.value}秒后重新获取` : '获取验证码'
)

// 发送验证码
const sendCode = async () => {
  if (!registerForm.value.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  // 模拟发送验证码
  ElMessage.success('验证码已发送')
  countdown.value = 60
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
    }
  }, 1000)
}

// 注册loading
const loading = ref(false)

const phoneError = ref('')
const codeError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const agreementError = ref('')

const validateForm = () => {
  let isValid = true
  // 重置错误信息
  phoneError.value = ''
  codeError.value = ''
  passwordError.value = ''
  confirmPasswordError.value = ''
  agreementError.value = ''

  // 手机号验证
  if (!registerForm.value.phone) {
    phoneError.value = '请输入手机号'
    isValid = false
  } else if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
    phoneError.value = '请输入正确的手机号'
    isValid = false
  }

  // 验证码验证
  if (!registerForm.value.code) {
    codeError.value = '请输入验证码'
    isValid = false
  } else if (!/^\d{6}$/.test(registerForm.value.code)) {
    codeError.value = '验证码为6位数字'
    isValid = false
  }

  // 密码验证
  if (!registerForm.value.password) {
    passwordError.value = '请设置密码'
    isValid = false
  } else if (registerForm.value.password.length < 6) {
    passwordError.value = '密码长度不能小于6位'
    isValid = false
  }

  // 确认密码
  if (!registerForm.value.confirmPassword) {
    confirmPasswordError.value = '请确认密码'
    isValid = false
  } else if (registerForm.value.confirmPassword !== registerForm.value.password) {
    confirmPasswordError.value = '两次输入的密码不一致'
    isValid = false
  }

  // 协议验证
  if (!registerForm.value.agreement) {
    agreementError.value = '请阅读并同意用户协议和隐私政策'
    isValid = false
  }

  return isValid
}

// 处理注册
const handleRegister = async () => {
  if (validateForm()) {
    try {
      loading.value = true
      // 模拟注册请求
      await new Promise(resolve => setTimeout(resolve, 1500))
      ElMessage.success('注册成功')
      router.push('/login')
    } catch (error) {
      ElMessage.error('注册失败，请稍后重试')
      console.error('注册错误：', error)
    } finally {
      loading.value = false
    }
  }
}

// 查看协议
const showAgreement = () => {
  // 显示用户协议
}

const showPrivacy = () => {
  // 显示隐私政策
}

// 去登录
const toLogin = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.register-container {
  display: flex;
  height: 100vh;
  
  .left-section {
    flex: 1;
    background: linear-gradient(135deg, #1890ff 0%, #1890ff 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    
    .content {
      text-align: center;
      h1 {
        font-size: 3rem;
        margin-bottom: 1rem;
      }
      p {
        font-size: 1.2rem;
        opacity: 0.9;
      }
    }
  }

  .right-section {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;

    .register-form {
      width: 400px;
      padding: 40px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

      h2 {
        text-align: center;
        margin-bottom: 30px;
        color: #333;
      }

      .form-group {
        margin-bottom: 20px;
        position: relative;

        input {
          width: 100%;
          padding: 12px;
          border: 1px solid #ddd;
          border-radius: 4px;
          outline: none;
          transition: border-color 0.3s;
          box-sizing: border-box;

          &:focus {
            border-color: #1890ff;
          }

          &.error {
            border-color: #ff4d4f;
          }
        }

        &.verify-code {
          display: flex;
          gap: 10px;

          input {
            flex: 1;
          }

          .code-btn {
            width: 120px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;

            &:disabled {
              background: #b3d7ff;
              cursor: not-allowed;
            }
          }
        }
      }

      .agreement-group {
        margin: 20px 0;
        
        label {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #666;
        }

        a {
          color: #1890ff;
          text-decoration: none;
          
          &:hover {
            text-decoration: underline;
          }
        }
      }

      .error-message {
        color: #ff4d4f;
        font-size: 12px;
        margin-top: 4px;
        display: block;
      }

      .register-btn {
        width: 100%;
        padding: 12px;
        background: #1890ff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        transition: background 0.3s;

        &:hover {
          background: #096dd9;
        }

        &:disabled {
          background: #b3d7ff;
          cursor: not-allowed;
        }
      }

      .login-link {
        margin-top: 16px;
        text-align: center;
        font-size: 14px;
        
        a {
          color: #1890ff;
          text-decoration: none;
          
          &:hover {
            text-decoration: underline;
          }
        }
      }

      .loading-spinner {
        width: 16px;
        height: 16px;
        border: 2px solid rgba(255, 255, 255, 0.7);
        border-top: 2px solid white;
        border-radius: 50%;
        animation: spin 0.6s linear infinite;
        display: inline-block;
        margin-right: 8px;
        vertical-align: middle;
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
